<template>
  <span>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="27%">
      <el-form :model="form" label-width="100px" ref="taskForm" :rules="rules">
        <el-form-item label="名称:" prop="task_name">
          <div style="width: 250px;">
            <el-input v-model="form.task_name" autocomplete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="负责人:">
          <div style="width: 250px;">
            <el-input v-model="form.owner" autocomplete="off"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="描述:">
          <div style="width: 250px">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.description">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="计划周期">
          <el-date-picker style="width: 250px"
            v-model="form.fdate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="timestamp"
            @change="handleDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="选择用例集:">
          <div style="width: 500px">
            <el-radio-group v-model="form.select_case" @change="handleRadioChange">
              <el-radio label="1">包含全部用例
                <p>覆盖全部可用用例（共计{{number}}个），如果</p> <p>用例集库有新增的用例，会自动加入到本计划中</p>
              </el-radio>
              <el-radio label="2">手动圈选用例集</el-radio>
            </el-radio-group>
            <div style="display:inline-block;horiz-align:left">优先级：
              <el-select style="width: 200px" :disabled="form.select_case !=='2'" v-model="form.priority" multiple placeholder="用例等级" @change="handlePriority">
                <el-option
                  v-for="item in priorityList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div style="display:inline-block;horiz-align:left">标签：
              <el-select style="width: 200px" :disabled="form.select_case !=='2'" v-model="form.tag" multiple placeholder="请选择标签" @change="handleTag">
                <el-option
                  v-for="item in tagList"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </div>
            <div v-if="form.select_case === '2'"> 已选择 {{count}} 条用例</div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" style="width: 350px">
        <span>
          <el-button @click="cancel_btn">取消</el-button>
        </span>
        <span  style="position: relative;left: 30px;">
          <el-button type="primary" @click="confirm_btn">确认</el-button>
        </span>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import request from "@/utils/axios"
import getQueryString from '@/utils/getCookies'
const getCookies = getQueryString.getCookie
export default {
  name: 'CreateTask',
  props: {
    title: {
      type: String,
      default: ''
    },
    caseId: {
      type: Number,
      default: 0
    },
    taskListData: {
      type: Array,
      default: () => []
    }
  },
  data(){
    return {
      taskId: 0,
      number: 100,
      count: 0,
      dialogFormVisible: false,
      form: {
        task_name: '',
        owner: '',
        description: '',
        fdate: [],
        select_case: '1',
        priority: [],
        tag: []
      },
      priorityList: [{
        value: '1',
        label: 'P0'
      },{
        value: '2',
        label: 'P1'
      },{
        value: '3',
        label: 'P2'
      }],
      tagList: [],
      rules: {
        task_name: [
          {required: true, message: '请输入测试任务名称', trigger: 'blur'},
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    showDialog: function (index=0, row={}) {
      if (this.title === '编辑测试任务') {
        this.taskId = row.id
        this.getTaskFormData(this.taskId)
        this.getCountByCondition(this.caseId, this.form.priority, this.form.tag)
      } else {
        // 点击创建测试任务，行id即caseId
        this.getCountByCondition(row.id)
      }
      this.dialogFormVisible = true;
    },
    getTaskFormData: function (taskId) {
      const taskData = this.taskListData.find(item => item.id === taskId)
      console.log('taskData:' , taskData)
      this.form.task_name = taskData.title
      this.form.owner = taskData.owner
      this.form.description = taskData.description
      let chooseContentObj = JSON.parse(taskData.chooseContent)
      if (chooseContentObj.priority.length > 0 || chooseContentObj.resource.length > 0) {
        this.form.select_case = '2'
      } else { this.form.select_case = '1'}
      this.form.priority = chooseContentObj.priority
      this.form.tag = chooseContentObj.resource
      if (taskData.expectStartTime && taskData.expectEndTime) {
        this.form.fdate = [Number(this.dateToTimeStamp(taskData.expectStartTime)), Number(this.dateToTimeStamp(taskData.expectEndTime))]
      } else {
        this.form.fdate = ''
      }
    },
    dateToTimeStamp: function (str_time) {
      const date = new Date(str_time)
      return date.getTime()
    },
    cancel_btn(){
      this.dialogFormVisible = false
    },
    confirm_btn(){
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          let values = this.form
          values.chooseContent = JSON.stringify({
            priority:
              values.chooseContent === '0' ? ['0'] : this.form.priority,
            resource: this.form.tag,
          });
          this.saveTask(values)
          this.dialogFormVisible = false
        } else {
          alert('任务名称必填！')
          this.dialogFormVisible = true
        }
      })
    },
    saveTask: function (values) {
      let params = {
        caseId: this.caseId,
        creator: getCookies('username'),
        chooseContent: values.chooseContent,
        description: values.description,
        expectStartTime: values.fdate? this.form.fdate[0]:"",
        expectEndTime: values.fdate? this.form.fdate[1]:"",
        owner: values.owner,
        title: values.task_name
      }
      let url = `/record/create`
      if (this.title === '编辑测试任务') {
        url = `/record/edit`;
        delete params.caseId;
        delete params.creator;
        params.id = this.taskId;
        params.modifier = getCookies('username');
      }
      request(url, { method: 'POST', body: params }).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: res.msg
          });
          this.$emit('getRecordList', this.caseId)
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      });
    },
    getCountByCondition: function (caseId=this.caseId, priority=[], tag=[]) {
      let url = `/case/countByCondition`
      request(url, {
        method: 'GET',
        params: {
          caseId: caseId? caseId: this.caseId,
          priority: priority || [],
          resource: tag || [],
        }
      }).then(res => {
        if (res.code === 200) {
          console.log('条件筛选用例：',res.data.count)
          this.number = res.data.totalCount
          this.count = res.data.count? res.data.count: 0
          this.tagList = res.data.taglist.map((item) => {
            return item
          })
        }
      })
    },
    initDate: function (){
      if (!this.form.fdate) {
        this.form.fdate = []
      }
    },
    handleDate: function (value) {
      if (!value) {
        this.initDate()
      } else {
        this.form.fdate = value
      }
    },
    handleRadioChange: function (value) {
      this.getCountByCondition()
      if (value === '1') {
        this.form.priority = ''
        this.form.tag = []
      }
    },
    handlePriority: function (value) {
      this.getCountByCondition(this.caseId, value,this.form.tag)
    },
    handleTag: function (value) {
      this.getCountByCondition(this.caseId, this.form.priority, value)
    },
  }
}
</script>

<style scoped>
.el-radio{
  display: block;
  line-height: 23px;
  white-space: normal;
  margin-right: 0;
}
</style>
